package it.afs.worklog.persist.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

import it.afs.persist.hibernate.HibernateUtils;
import it.afs.worklog.persist.Dao;
import it.afs.worklog.persist.DaoFactory;

public class HibernateDaoFactory extends DaoFactory
{
	private static final Log log = LogFactory.getLog(HibernateDaoFactory.class);
	
	private Session session;
	private Transaction tx;

	@Override
	public void init()
	{
		session = HibernateUtils.getSessionFactory().getCurrentSession();
		log.debug("Hibernate session initialized");
	}
	
	@Override
	public void beginUnit()
	{
		tx = session.beginTransaction();
		log.debug("Work unit started");
	}
	
	@Override
	public boolean endUnit()
	{
		if(tx != null && tx.isActive())
		{
			try {
				tx.commit();
				log.debug("Work unit ended");
				return true;
			} catch (Exception e) {
				log.trace(e);
				return false;
			}
		} else
			return false;
	}
	
	@Override
	public void cancelUnit()
	{
		if(tx != null && tx.isActive())
		{
			try {
				tx.rollback();
				log.debug("Work unit cancelled");
			} catch (Exception e) {
				log.trace(e);
			}
		}
	}

	@Override
	public Dao getDao()
	{
		return new HibernateDao(session);
	}
}